<template>
<div>
  <el-form class="projectForm" ref="elForm" :model="formData" :rules="rules" size="medium" label-width="100px">
    <el-tabs    v-model="activeName" @tab-click="TabClick">
      <el-tab-pane label="基本内容" name="first">
        <el-form-item label="项目名称" prop="fName">
          <el-input v-model="form.fName" type="textarea" placeholder="请输入内容" />
        </el-form-item>
        <el-form-item label="起始日期" prop="fCreatedate">
          <el-date-picker clearable
                          v-model="form.fCreatedate"
                          type="date"
                          value-format="yyyy-MM-dd"
                          placeholder="请选择起始日期">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="结束日期" prop="fEnddate">
          <el-date-picker clearable
                          v-model="form.fEnddate"
                          type="date"
                          value-format="yyyy-MM-dd"
                          placeholder="请选择结束日期">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="描述信息" prop="fDesc">
          <el-input v-model="form.fDesc" type="textarea" placeholder="请输入内容" />
        </el-form-item>
        <el-form-item size="large">
          <el-col>
            <el-button type="primary" circle @click="Next(2)" icon="el-icon-right"></el-button>
          </el-col>
        </el-form-item>
      </el-tab-pane>
      <el-tab-pane label="上传数据" name="second">
        <el-row>
          <el-form-item label="项目范围">
            <el-upload
              class="upload-demo"
              ref="upload"
              drag
              action
              multiple
              :disabled="false"
              :auto-upload="false"
              :limit="5"
              :on-success="handleFilUploadSuccess"
              :on-remove="handleRemove"
              :on-change="fileChange"
            >
              <i class="el-icon-upload"></i>
              <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
              <div class="el-upload__tip" slot="tip">
                <div class="el-upload__tip" slot="tip">
                  <p style="line-height: 12px;">1.请上传zip压缩包；</p>
                  <p style="line-height: 12px;">2.确保上传的数据为2000国家大地坐标系；</p>
                  <p style="line-height: 12px;">3.上传的zip文件至少包含：.shp、.dbf、.shx、.prj文件。</p>
                </div>
              </div>
            </el-upload>
          </el-form-item>
        </el-row>
        <el-form-item size="large">
          <el-col :span="12">
            <el-button type="primary" circle @click="Next(1)" icon="el-icon-back"></el-button>
          </el-col>
          <el-col :span="12">
            <el-button type="primary" circle @click="Next(3)" icon="el-icon-right"></el-button>
          </el-col>
        </el-form-item>
      </el-tab-pane>
      <el-tab-pane label="建立映射关系" name="third">
        <el-row>
        <div class="left-layers">
            <a v-for="(item,index) in fieldMap.layerNames"
               :id="index" :key="item"
               @click="changeIndex(index) "
               :class="['normal',index==fieldMap.selectLayerIndex ? 'active' : 'normal']">{{item}}</a>
        </div>
        <div class="right-fields">
          <div v-for="(item,index) in fieldMap.layers" v-show="item.visible">
            <div class="mapping-item" id="layerReName"><a>图层别名</a>
              <input type="text" name="layerReName" :value="item.name">
            </div>
            <div class="mapping-item" id="showfields"><a>显示字段</a>
              <div class="fields-li" v-for="(item,index) in item.fields" :title="item">
                <span class="fields-checked" @click="changeCheck($event,'show',item)" type="checked"></span>
                <span class="fields-title">{{item.name}}</span>
              </div>
            </div>
            <div class="mapping-item" id="surveyfields"><a>调查字段</a>
              <div class="fields-li" v-for="(item,index) in item.fields" :title="item">
                <span class="fields-checked" @click="changeCheck($event,'survey',item)" type="checked"></span>
                <span class="fields-title">{{item.name}}</span>
              </div>
            </div>
            <div class="mapping-item" id="distfields"><a>分发字段</a>
              <div class="fields-li" v-for="(item,index) in item.fields" :title="item">
                <span class="fields-checked" @click="changeCheck($event,'dist',item)" type="checked"></span>
                <span class="fields-title">{{item.name}}</span>
              </div>
            </div>
          </div>
        </div>
        </el-row>
        <el-form-item size="large">
          <el-col :span="12">
            <el-button type="primary" circle @click="Next(2)" icon="el-icon-back"></el-button>
          </el-col>
          <el-col :span="12">
            <el-button type="primary" circle @click="Next(4)" icon="el-icon-right"></el-button>
          </el-col>
        </el-form-item>
      </el-tab-pane>
      <el-tab-pane label="分配单位" name="fourth">
        <el-row>
          <div class="class-group">
            <div class="union-li" v-for="(item,index) in deptList" :class="{'selected':item.checked}"
                 :id=item.deptId @click="changeCheckDept($event,index,item)">
              <span class="union-wrap">{{item.deptName}}</span>
            </div>
          </div>
        </el-row>
        <el-form-item size="large">
          <el-col :span="12">
            <el-button type="primary" @click="Next(3)">上一步</el-button>
          </el-col>
          <el-col :span="12">
            <el-button type="primary" @click="Submit()">提交</el-button>
          </el-col>
        </el-form-item>
      </el-tab-pane>
    </el-tabs>
  </el-form>
</div>
</template>

<script>
import { addProject, getProject } from '@/api/survey/project'
import {addLayerMeta} from '@/api/survey/layer'
import { listDept } from "@/api/system/dept";
import { addProjectLayer, addProjectUnit, saveShpFile, uploadShpFile } from '@/api/survey/basic'

export default {
  name: 'createProject',
  components:{},
  data(){
    return {
      shpPath:"",
      fieldMap:{
        selectLayerName:"",
        selectLayerIndex:0,
        layerNames:[],
        //fieldNames:[],
        layers:[],
      },
      dept:null,
      deptList:[],
      fileList:[],
      config: {
        "newprojectname": null,
        "layerlist": [],
        "fieldlist": null,
        "photoconfig": null
      },
      activeName: 'first',
      formData:{},
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        fName: [
          { required: false, message: "项目名称不能为空", trigger: "blur" }
        ],
      }
    }
  },
  props: {
    show: {
      type: Object,
      default: null
    }
  },
  mounted() {

  },
  methods: {
    /** 查询部门列表 */
    getDeptList() {
      let that=this;
      listDept(this.queryParams).then(response => {
        //that.deptList = that.handleTree(response.data, "deptId");
        that.deptList = response.data;
        for(let i in that.deptList){
          that.$set(that.deptList[i],'checked',false);
          //that.deptList[i].checked=false;
        }
      });
    },
    Submit(){
      let that=this;
      that.form.fState=1;
      addProject(that.form).then(response => {
        that.$modal.msgSuccess("新增成功");
        that.show.showCreateNew = false;
        //why20221029
        if(that.dept!=null){
          let projectUnit={
            fProjectid:response.data,
            fUnitid:that.dept.deptId
          };
          addProjectUnit(projectUnit).then(response => {
            //that.$modal.msgSuccess("新增成功");
          });
        }
        if(that.shpPath!=null&&that.shpPath!=""){
          saveShpFile({"outZipName":that.shpPath}).then(res => {
            if(res.code==200){
              let layernames=res.data;
              for(let l in layernames){
                let layername=layernames[l];
                let realname=layername.substring(layername.indexOf("_")+1,layername.lastIndexOf("_"));
                for(let i in that.config.layerlist) {
                  let layer = that.config.layerlist[i];
                  if(layer.fName==realname){
                    layer.fName=layername;
                  }
                }
              }
            }
            for(let i in that.config.layerlist){
              let layer=that.config.layerlist[i];
              addLayerMeta(layer).then(response => {
                //that.$modal.msgSuccess("新增成功");
                let projectLayer={
                  fProjectid:projectUnit.fProjectid,
                  fLayerid:response.data
                }
                addProjectLayer(projectLayer).then(response => {
                  //that.$modal.msgSuccess("新增成功");
                });
              })
            }

          });
        }


      });
    },
    //单位选择
    changeCheckDept(e,index,item){
      let that=this;
      that.dept=item;
      for(let i in that.deptList){
        let item0=that.deptList[i];
        if(parseInt(i)==index)
          item0.checked=true;
        else
          item0.checked=false;
      }
    },
    //字段选择
    changeCheck(e,attr,item){
      let that=this;
      let checkflag = e.currentTarget.getAttribute("type");
      if (checkflag == "checked") {
        e.currentTarget.setAttribute("type", "unchecked");
        item[attr]=false;
      }
      if (checkflag == "unchecked") {
        e.currentTarget.setAttribute("type", "checked");
        item[attr]=true;
      }
    },
    //图层选择
    changeIndex(index) {
      this.fieldMap.selectLayerIndex = index;
      //默认显示第一个
      this.fieldMap.selectLayerName=this.fieldMap.layers[index].name;
      for(let i in this.fieldMap.layers){
        if(i==index)
          this.fieldMap.layers[index].visible=true;
        else
          this.fieldMap.layers[i].visible=false;
      }
    },
    saveFields(){
      let that=this;
      for(let i in that.fieldMap.layers){
        let layer=that.fieldMap.layers[i];
        let fields=layer.fields;
        let fieldNames=[];
        let showFields = [];
        let surveryFields = [];
        let distFields = [];
        for(let j in fields) {
          let field = fields[j];
          fieldNames.push(field.name.toLowerCase());
          if (field.show)
            showFields.push(field.name.toLowerCase());
          if(field.survey)
            surveryFields.push(field.name.toLowerCase());
          if(field.dist)
            distFields.push(field.name.toLowerCase());
        }
        that.config.layerlist[i]= {
          fName: layer.name,
          fRname: layer.name,
          fLayertype:layer.type,
          fUniquefield:'gid',
          fCreateTime:Math.round(new Date().getTime()/1000),
          fFields: JSON.stringify(fieldNames),
          fShowfields: JSON.stringify(showFields.toString()),
          fSurveyfields: JSON.stringify(surveryFields.toString()),
          fDistfields: JSON.stringify(distFields.toString())
        }
      }
    },
    TabClick(tab) {
      let that = this
      that.Next(tab.index - 0 + 1)
    },
    Next(index) {
      let that = this
      switch (index) {
        case 1:
          that.activeName = 'first'
          break
        case 2:
          that.activeName = 'second'
          break
        case 3:
          that.activeName = 'third'
          break
        case 4:
          //打开生态红线数据
          that.saveFields();
          that.getDeptList();
          that.activeName = 'fourth'
          break
        case 5://自然保护区
          that.activeName = 'fifth'
          break
        case 6://水源地保护
          //that.ZoomToExtent()
          //that.openData('waterprotect',false)
          that.activeName = 'sixth'
          break
        case 7://国土空间规划
          //that.ZoomToExtent()
          //that.openData('landspace',false)
          that.activeName = 'seventh'
          break
      }
    },

    handleFilUploadSuccess(res, file, fileList) {
      console.log(res, file, fileList)
    },
    handleRemove(file, fileList) {
      console.log(file, fileList)
    },
    // 文件上传成功时的函数
    fileChange(file) {
      let that = this
      this.fileList = [];
      let existFile = this.fileList.slice(0, this.fileList.length - 1).find(f => f.name === file.name)//如果文件名重复
      if (existFile) {
        this.$message.error('当前文件已经存在!')
        this.fileList.pop()
      } else {
        this.fileList.push(file)
      }


      let fd = new FormData()
      that.fileList.forEach(item => {
        //文件信息中raw才是真的文件
        fd.append('files', item.raw)
      })

      uploadShpFile(fd).then(res => {
        if (res.code === 200) {
          if (res.data.status === "error") {
            this.$message.error(res.data.msg)
          } else if (res.data.status === 400) {
            this.$message.error("上传shp文件有错误，请检查文件是否正确。  " + res.data.message)
          }
          if (res.data.queryData.length > 0) {
            that.fieldMap.layerNames = [];
            that.fieldMap.layers = [];
            let shps = res.data.queryData;
            that.shpPath=res.url;
            for (let i in shps) {
              let props = shps[i].data.props;
              let name = shps[i].data.name;
              let a=shps[i].data.type.split(".");
              let type=a[a.length-1];
              that.fieldMap.layerNames.push(name);
              let fields = [];
              if (props.length > 0) {
                let prop = props[0];
                let format = new ol.format.WKT()
                let feature = format.readFeature(prop.the_geom);
                for (let fieldname in prop) {
                  fields.push({
                    name: fieldname,
                    show: true,
                    survey: true,
                    dist: true
                  });
                }
              }
              that.fieldMap.layers.push({
                name: name,
                type:type,
                fields: fields,
                visible: false
              });
            }
            //默认显示第一个
            that.fieldMap.selectLayerIndex = 0;
            that.fieldMap.selectLayerName = that.fieldMap.layers[0].name;
            //that.fieldMap.fieldNames=that.fieldMap.layers[0].fields;
            that.fieldMap.layers[0].visible = true;
          }
          this.$message.success('上传成功')
          //this.mcShow.uploadshp = 'close'
        } else {
          this.$message.error('失败')
        }
      });
    },
  }
}
</script>

<style scoped>
.class-group {
  width: 100%;
}
.union-li {
  display: -webkit-box;
  display: -ms-flexbox;
  display: flex;
  float: left;
  padding: 25px 0px;
  width: auto;
  background-color: #e2f4ff;
  margin: 5px 10px;
  border-radius: 5px;
  text-align: center;
  height: 70px;
}
.union-li.selected {
  background: url(~@/assets/images/icon/check-true.png) no-repeat right top #e2f4ff;
  border: 1px solid #0b0;
  box-shadow: 0px 0px 5px #0b0;
}
.union-wrap {
  padding-right: 30px;
  cursor: pointer;
  background-color: #e2f4ff;
  padding-left: 30px;
}
.left-layers{
  width: 30%;
  float: left;
}
.left-layers a.active {
  border: 1px solid #0b0;
  box-shadow: 0px 0px 5px #0b0;
}
.left-layers a {
  display: block;
  /* border-bottom: 1px solid; */
  margin: 5px 0px;
  /* background-color: lightblue; */
  padding: 3px 5px;
  width: 80%;
  cursor: pointer;
  background-color: #e2f4ff;
}
.right-fields{
  width: 70%;
  float: left;
  border-left: 1px solid;
}
.mapping-item {
  width: 100%;
  float: left;
  padding: 0px 20px;
  margin: 10px 0px;
}
.mapping-item a {
  padding: 5px 0px;
  display: block;
}
.fields-li {
  float: left;
  padding: 25px 25px;
}
.fields-checked[type=checked] {
  background: url("~@/assets/images/icon/checkedbox.png") no-repeat center;
}
.fields-checked[type=unchecked] {
  background: url("~@/assets/images/icon/checkbox.png") no-repeat center;
}
.fields-checked {
  float: left;
  display: block;
  width: 30px;
  height: 30px;
}
.fields-title {
  line-height: 30px;
}
</style>
